<template>
    <div id="menu-list">
        <div v-if="iconFileList.length>0" >
            <div class="top">
                <img src="../../assets/img/file/check_normal.png" alt="" v-if="!allCheck" @click="checkAll">
                <img src="../../assets/img/file/check_highlight.png" alt="" v-else @click="unCheckAll">
                <p>全选</p>
            </div>
            <ul>
                <li
                        class="iconfileitem"
                        v-for="(item,index) in iconFileList"
                        :key="index"
                        @click.exact="bigiconClicked(item,index,false)"
                        :class="indexData.indexOf(index)!=-1?'bigiconclickeded':''"
                >
                    <img src="../../assets/img/file/uncheck.png" class="uncheck">
                    <img src="../../assets/img/file/checked.png" alt="" v-show="indexData.indexOf(index)!=-1" >
                    <div style="display: flex">
                        <span :class="'file-icon '+item.iconcls" class="icon"></span>
                        <el-tooltip
                                class="item"
                                effect="dark"
                                v-if="item.fileName && abslength(item.fileName) > 20"
                                :content="item.fileName"
                                placement="bottom"
                        >
                            <p class="name" @click.stop @click="handleCellClickFun(item)">{{ item.fileName.substring(0,$getFontShowLength(item.fileName,20))+'...'}}</p>
                        </el-tooltip>
                        <p class="name" v-else @click.stop @click="handleCellClickFun(item)">{{ item.fileName }}</p>
                    </div>
                    <div class="folder-box-options">
                        <el-popover placement="right"
                                    class="setting"
                                    trigger="hover"
                                    v-if="isshow == '我的文档' || isshow == '同事共享'"
                                    v-show="item.isFavorites != undefined"
                        >
                            <ul class="settingOptions">
                                <li @click="downloadFile(item)" v-show="item.fileType=='0'">
                                    <i class="fa fa-download" aria-hidden="true"></i>
                                    下载
                                </li>
                                <li @click="previewFile(item)" v-show="item.fileType=='0'">
                                    <i class="fa fa-eye" aria-hidden="true"></i>
                                    预览
                                </li>
                                <li @click="handleDelete(item)" v-show="isshow == '我的文档'">
                                    <i class="fa fa-trash-o" aria-hidden="true"></i>
                                    删除
                                </li>
                                <li @click="collectFile(item)" v-show="item.isFavorites == '0'">
                                    <i class="fa fa-star-o" aria-hidden="true"></i>
                                    收藏
                                </li>
                                <li @click="retweet(item)" v-show="isshow == '同事共享'">
                                    <i class="fa fa-retweet" aria-hidden="true"></i>
                                    转存
                                </li>
                                <li @click="renameHandle(item)" v-show="isshow == '我的文档'">
                                    <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                                    重命名
                                </li>
                                <li @click="collectFile(item)" v-show="item.isFavorites == '1'">
                                    <i class="fa fa-star" aria-hidden="true"></i>
                                    取消收藏
                                </li>
                                <li @click="shareFile(item)" v-show="isshow == '我的文档'">
                                    <i class="fa fa-share-alt" aria-hidden="true"></i>
                                    内部分享
                                </li>
                                <li @click="outShareFile(item)" v-show="isshow == '我的文档'">
                                    <i class="fa fa-share-alt-square" aria-hidden="true"></i>
                                    外链分享
                                </li>
                                <li @click="fileHistory(item)" v-show="item.fileType=='0' && isshow == '我的文档'">
                                    <i class="fa fa-history" aria-hidden="true"></i>
                                    历史记录
                                </li>
                                <li @click="companyShare(item)" v-show="isshow == '我的文档'">
                                    <i class="fa fa-share-square-o" aria-hidden="true"></i>
                                    公司分享
                                </li>
                                <li @click="partnerShare(item)" v-show="isshow == '我的文档'">
                                    <i class="fa fa-share" aria-hidden="true"></i>
                                    合作伙伴分享
                                </li>
                                <li  @click="fileMove(item)"  v-show='isshow=="我的文档"'>
                    <i class="fa fa-arrows" aria-hidden="true"></i>
                    移动文件
                  </li>
                            </ul>
                            <i slot="reference" class="iconfont" style="cursor: pointer;" @click.stop>&#xe679;</i>
                        </el-popover>
                        <el-popover placement="right"
                                    popper-class="filepopover"
                                    class="setting"
                                    trigger="hover"
                                    v-else
                                    v-show="isshow == '公司文档'"
                        >
                            <ul class="settingOptions">
                                <li @click="downloadFile(item)" v-show="item.fileType=='0'">
                                    <i class="fa fa-download" aria-hidden="true"></i>
                                    下载
                                </li>
                                <li @click="previewFile(item)" v-show="item.fileType=='0'">
                                    <i class="fa fa-eye" aria-hidden="true"></i>
                                    预览
                                </li>
                                <li @click="retweet(item)">
                                    <i class="fa fa-retweet" aria-hidden="true"></i>
                                    转存
                                </li>
                                <li  @click="fileMove(item)"  v-show='isshow=="我的文档"'>
                    <i class="fa fa-arrows" aria-hidden="true"></i>
                    移动文件
                  </li>
                                <!--<li @click="collectFile(item)" v-show="item.isFavorites == '0'">-->
                                    <!--<i class="fa fa-star-o" aria-hidden="true"></i>-->
                                    <!--收藏-->
                                <!--</li>-->
                                <!--<li @click="collectFile(item)" v-show="item.isFavorites == '1'">-->
                                    <!--<i class="fa fa-star" aria-hidden="true"></i>-->
                                    <!--取消收藏-->
                                <!--</li>-->
                            </ul>
                            <i slot="reference" class="iconfont" style="cursor: pointer;" @click.stop>&#xe679;</i>
                        </el-popover>
                    </div>
                </li>
            </ul>
        </div>
        <p class="noContent" v-else>
            <img src="../../assets/img/file/no2.png" alt="" v-show="tellyou.length>0">
            {{tellyou}}
        </p>
        <div class="download-box" v-if="$store.state.fileListDownBox==1">
          <span class="smaller-icon" @click="$store.commit('setFileListDownBox',2)"><i class="fa fa-compress" aria-hidden="true"></i></span>
        <span>正在下载中：</span><span style="color:red" @click="stopDownload"><i class='el-icon-circle-close'></i></span><br>
        <el-progress :percentage='$store.state.loadingList[0].percentComplete' :show-text="true"></el-progress>
    </div>
    <div class="download-box-small" v-if="$store.state.fileListDownBox==2">
      下载中：<span @click="$store.commit('setFileListDownBox',1)"><i class="fa fa-expand" aria-hidden="true"></i></span>
    </div>
    </div>
</template>
<script>
  export default {
    name: "bigIconShow",
    props: {
      bigIconShowData: Array,
      workmateDisable: Boolean,
      backflag:Boolean,
      filetable: Object
    },
    data() {
      return {
        iconFileList: [],
        menuitem: "",
        isloading: false,
        menuleft: "0",
        menutop: "0",
        isclick: [],
        data:[],
        checkdata:[],
        indexData:[],
        allCheck:false,
        tellyou:"",
        isshow:sessionStorage.getItem("currentBox"),
      };
    },
    mounted() {
      this.isloading = true;
      setTimeout(this.initData, 500);
      // console.log("wo shi ",this.backflag);
    },
    watch: {
      indexData:{
        handler:function (newVal, oldVal) {
          if(newVal.length == this.bigIconShowData.length){
            this.allCheck = true;
          }else{
            this.allCheck = false;
          }

        }
      },
      backflag:{
        handler: function(newVal, oldVal) {
          if (newVal !== oldVal) {
            if(newVal == true){
              this.data = [];
              this.checkdata = [];
            }
          }
        }
      },
      bigIconShowData: {
        handler: function(newVal, oldVal) {
            this.isloading = true;
            setTimeout(this.initData, 500);
        },
        deep:true
      }
    },
    methods: {
      retweet(data){
        this.$emit("retweet",data);
      },
      handleFileList(data) {
        console.log('!!!!!!!!!!!!!!!!!!!!!',data)
        let file_icon = '';
        let fileList=[];
        for (let i = 0; i < data.length; i++ ) {
          if (data[i].fileName == null) {
            continue;
          }
          let suffixTemp = data[i].fileName.split(".");
          if (suffixTemp.length > 1) {
            suffixTemp = suffixTemp[suffixTemp.length - 1];
            file_icon = "icon_list_" + suffixTemp;
          } else if (data[i].fileType === 0) {
            suffixTemp = "";
          } else {
            suffixTemp = null;
          }
          fileList.push({
            id: data[i].id,
            checked:data[i].checked,
            dirId: data[i].dirId,
            fileName: data[i].fileName,
            size: this.$getFileSize(data[i].fileSize),
            creatTime: data[i].creatTime == null ? "暂无数据" : data[i].creatTime,
            updateTime: data[i].updateTime == null ? "暂无数据" : data[i].updateTime,
            suffix: suffixTemp,
            fileHash: data[i].fileHash,
            fileType: data[i].fileType,
            iconcls: data[i].fileType == 1 ? "icon_list_folder" : file_icon,
            isFavorites: data[i].isFavorites,
            realName: data[i].realName,
            fileSize:data[i].fileSize,
          });
        }
        console.log('!!!!!!!!!!!!!!',fileList)
        return fileList;
      },
      companyShare(item){
        this.$emit("companyShare",item);
      },
      partnerShare(item){
        this.$emit("partnerShare",item);
      },
      unCheckAll(){
        this.allCheck=false;
        console.log("全选："+this.allCheck)
        this.bigIconShowData.forEach((val,key)=>{
          this.$set(val,"checked",false);
        })
        this.iconFileList.forEach((val,key)=>{
          this.$set(val,"checked",false)
        })
        this.indexData = [];
        this.checkdata = [];
        this.data = [];
        this.$emit("getSels",[]);
      },
      checkAll(){
        this.indexData = [];
        this.checkdata = [];
        this.data = [];
        this.allCheck=true;
        console.log("全选："+this.allCheck)
        this.iconFileList.forEach((val,key)=>{
          this.$set(val,"checked",true)
        })
        this.bigIconShowData.forEach((val,key)=>{
          this.$set(val,"checked",true);
          this.indexData.push(key);
          this.checkdata.push(val);
          this.data.push(val.id);
        })
        console.log(this.data.length,);
        if(this.data.length>0){
          this.isclick = this.data;
          this.$emit("getSels",this.checkdata);
        }
        console.log(this.bigIconShowData);
      },
      abslength( str ) {
        return str.replace(/[^\x00-\xff]/ig, '**').length;
      },
      initData() {
        let data = this.bigIconShowData;
        this.iconFileList = [];
        if (this.bigIconShowData == false) {
          return;
        }
        data=this.handleFileList(data);
        data.forEach((val,key)=>{
          // console.log(val);
          let icon = 'icon_list_' + val.suffix;
          if(val.checked == undefined){
            val.checked = false;
          }
          if(val.fileType == 1){
            val.iconcls = "icon_list_folder";
          }else{
            val.iconcls = icon;
          }
        })
        if(data.length == 0){
          this.tellyou = "暂无内容";
        }
        this.iconFileList = data;
        this.isloading = false;
        // console.log("data0", data);
      },
      bigiconClicked(item,index) {
        this.$emit("getSels",[]);
        item.checked = !item.checked;
        if(item.checked){
          this.indexData.push(index);
          this.data.push(item.id);
          this.checkdata.push(item);
        }else{
          console.log("data :"+JSON.stringify(this.data))
          console.log(this.indexData)
          console.log("this.checkdata:"+JSON.stringify(this.checkdata))
          if(this.data.length == 0) return; //从这就不走了
          if(this.indexData.length == 0) return;
          this.data.forEach((val,key)=>{
            if(val == item.id){
              this.data.splice(key,1);
            }
          })
          this.indexData.forEach((val,key)=>{
            if(val == index){
              this.indexData.splice(key,1);
            }
          })
          this.checkdata.forEach((val,key)=>{
            if(val.id == item.id){
              this.checkdata.splice(key,1);
            }
          })
        }
        if(this.data.length>0){
          this.isclick = this.data;
          this.$emit("getSels",this.checkdata);
        }
      },
      handleCellClickFun(item) {
        this.data = [];
        this.checkdata = [];
        this.$emit("handleCellClick",item)
      },
      downloadFile(item) {
        this.$emit("downloadFile",item)
      },
      stopDownload(){
                this.$emit("stopDownload");
    },
      /**
       * 获取文件类型
       * @param file
       */
      getType(file) {
        console.log(file);
        var filename = file;
        var index1 = filename.lastIndexOf(".");
        var index2 = filename.length;
        var type = filename.substring(index1 + 1, index2);
        console.log(type);
        return type;
      },
      getBlob(url) {
      return new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };
        xhr.send();
      });
    },
handleImageFile (url) {
    // 使用FileReader来处理
    console.log(url);
    const reader = new FileReader ();
    let _this=this;
    reader.addEventListener ('load', (e) => {
      console.log(e);
        const imgUrl = e.target.result;
        let imgNode = document.createElement('img');
        imgNode.src = imgUrl;
        console.log(imgNode);
        //imgNode.setAttribute('height', '100%');
        imgNode.setAttribute('width', '800px');
        imgNode.style.position='absolute';
        imgNode.style.top='50%';
        imgNode.style.left='50%';
        imgNode.style.transform='translate(-50%, -50%)';
        // imgNode.setAttribute('transform', 'translate(-50%, -50%)');
        _this.createPreviewItem(imgNode);
    });
    reader.readAsDataURL(url);
},
handlePdfFile (url) {
    // 使用URL来处理
    const pdfUrl = url;
    let embedNode = document.createElement('embed');
    embedNode.src = pdfUrl;
    embedNode.setAttribute('width', '100%');
    embedNode.setAttribute('height','100%')
    // embedNode.setAttribute('margin-top', '100px');
    embedNode.style.position='absolute';
        embedNode.style.left='0px';
        embedNode.style.top='0px';
        embedNode.style.bottom='0px';
        embedNode.style.right='0px';
    console.log(embedNode);
    this.createPreviewItem(embedNode);
},
createPreviewItem (newNode) {
  console.log(newNode);
  let body=document.querySelector("body");
    let box=document.querySelector(".preview-box");
    let iSpan=document.querySelector('.preview-box>span');
    let myul=document.querySelector(".preview-box__ul");
    myul.appendChild(newNode);
    iSpan.addEventListener("click", function(){
          box.style.display = "none";
          myul.removeChild(newNode);
	})

     box.style.display='block';
},
      previewFile(file){
        console.log(file);
        // let arr = ["png","jpg","pdf","gif","txt"];
        let arr = ["txt"];
        if (arr.indexOf(this.getType(file.fileName)) != -1) {
          if(this.$store.state.ipfsArray==0){
            this.$message.error('获取请求路径失败,请检查网络或呼叫管理员');
          }else{
            this.getBlob(this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash).then(blob => {
                this.imgurl = window.URL.createObjectURL(blob);
                console.log(this.imgurl)
                if(this.imgurl != ""){
                  window.open(this.imgurl,"_blank")
                }
            });
          }
        } else if(file.suffix.toLowerCase() == "mp4" || file.suffix.toLowerCase() == "webm" || file.suffix.toLowerCase() == "ogg" ){
           let url = this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash;
           console.log(url);
          let routeUrl = this.$router.resolve({
            path: "/mp4Play",
            query: {url:url}
          });
          window.open(routeUrl.href, '_blank');
        }else if(file.suffix.toLowerCase() == "flv"){
          let url = this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash;
          console.log(url);
          let routeUrl = this.$router.resolve({
            path: "/videoPlay",
            query: {url:url}
          });
          window.open(routeUrl.href, '_blank');
        }else if(file.suffix.toLowerCase() == "pdf"){
          this.getBlob(this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash).then(blob => {
                this.imgurl = window.URL.createObjectURL(blob);
                this.handlePdfFile(this.imgurl)
            });
        }else if(file.suffix.toLowerCase() == "png"||file.suffix.toLowerCase() == "jpg"||file.suffix.toLowerCase() == "gif"){
          this.getBlob(this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash).then(blob => {
                // this.imgurl = window.URL.createObjectURL(blob);
                this.handleImageFile(blob);
            });
        }else{
          this.$message("当前文件不支持预览，请下载查看");
        }
      },

      handleDelete(item) {
        this.data = [];
        this.checkdata = [];
        this.$emit("handleDelete",item);
      },
      shareFile(item) {
        this.$emit("shareFile",item);
      },
      outShareFile(item){
        console.log(this.$parent)
        this.$emit("outShareFile",item);
      },
      renameHandle(item) {
        console.log(item);
        this.$emit("renameHandle",item);
      },
      fileHistory(item) {
        this.$emit("fileHistory",item);
      },
      collectFile(item){
        this.$emit("collectFile",item);
      },
      fileMove(item){
        let array=[item]
        this.data = [];
        this.checkdata = [];
        this.$emit('fileMove',array);
      }
    }
  };
</script>
<style lang="scss">
</style>
<style scoped lang="scss">
    #menu-list{
      .download-box{
        position: fixed;
        z-index: 10;
        bottom: 20px;
        right: 20px;
        width: 330px;
        padding: 14px 26px 14px 13px;
    border-radius: 8px;
    box-sizing: border-box;
    border: 1px solid #ebeef5;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    .smaller-icon{
      position: absolute;
      right:5px;
      top:10px;
    }
      }
      .download-box-small{
      position: fixed;
      z-index: 20;
      bottom: 20px;
        right: 20px;
        border: 1px solid #ebeef5;
    background-color: #549DE8;
    width: 70px;
    border-radius: 4px;
    padding: 5px 8px 5px 5px;
    }
        .file-icon{
            background: url("/static/bigicon.png") no-repeat -196px 0px;
            display: inline-block;
            width: 28px;
            height: 29px;
            margin-right:10px;
            margin-left: 21px;
        }
        .top{
            height: 72px;
            border-bottom:1px solid #eee;
            padding-left: 40px;
            display: flex;
            align-items: center;
            img{
                margin-right: 31px;
            }
        }
        ul{
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            margin-top:20px;
            /*margin-left: 20px;*/
            li {
                box-sizing: border-box;
                border: 1px solid #F6F6F6;
                margin-bottom: 20px;
                margin-left: 20px;
                width: 256px;
                height: 54px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                position: relative;
            }
            .bigiconclickeded{
                border:1px solid #549DE8;
            }
            .name{
                margin-left:10px;
                max-width: 160px;
                overflow:hidden;
                text-overflow:ellipsis;
                white-space:nowrap
            }
            .name:hover{
                text-decoration: underline;
            }
            .folder-box-options{
                margin-right: 10px;
            }
            .uncheck{
                display: none;
            }
            img{
                position: absolute;
                right: 0;
                top:0;
            }
            .iconfont{
                margin-right: -5px;
                margin-top: 15px;
                display: none;
            }
            li:hover{
                border:1px solid #549DE8;
                box-sizing: border-box;
                cursor: pointer;
            }
            li:hover .iconfont{
                display: block;
            }
            li:hover .shareicon{
                opacity: 1;
            }
            li:hover .uncheck{
                display: block;
            }
        }
        .noContent{
            display: flex;
            flex-direction: column;
            margin-top: 150px;
            justify-content: center;
            align-items: center;
            color:#B4B4B4;
            font-size: 18px;
        }
    }
</style>
